#!/usr/bin/env python
# encoding: utf8
import os, sys, urllib, urllib2,cookielib




########################################################################
class GetRules:
    """
    下载CCS技术支持系统中的规范公约等
    """

    #----------------------------------------------------------------------
    def __init__(self,debuglevel=1):
        """Constructor"""
        self.data=None
        self.temppage=None
        self.debuglevel=debuglevel
        self.cookie=cookielib.CookieJar()

        #设置并安装opener
        self.__buildopener()

        self.setcookie()
        self.setdebuglevel()

        self.__install_opener()




    #----------------------------------------------------------------------
    def login(self,url='',userpass={},rightkeyword='',wrongkeyword=''):
        """登录"""
        if not url:
            print "Url can\'t be empty"
            return False
        self.url=url
        self.rightkeyword=rightkeyword
        self.wrongkeyword=wrongkeyword
        self.data=urllib.urlencode(userpass)

        self.__post()
        self.__ask()

    #----------------------------------------------------------------------
    def logout(self):
        """注销"""

    #----------------------------------------------------------------------
    def setdebuglevel(self):
        """是否显示连接过程"""
        self.opener.add_handler(urllib2.HTTPHandler(debuglevel=self.debuglevel))
        self.opener.add_handler(urllib2.HTTPSHandler(debuglevel=self.debuglevel))

    #----------------------------------------------------------------------
    def setcookie(self):
        """设置cookie"""
        self.opener .add_handler(urllib2.HTTPCookieProcessor(self.cookie))

    #----------------------------------------------------------------------
    def __install_opener(self):
        """设置opener"""

        urllib2.install_opener(self.opener)

    #----------------------------------------------------------------------
    def __buildopener(self):
        """创建opener"""
        self.opener = urllib2.build_opener()

    #----------------------------------------------------------------------
    def __post(self):
        """提交并获取数据数据"""
        self.req=urllib2.Request(self.url,self.data)
        try:
            self.res=urllib2.urlopen(self.req)
        except URLError, e:  
            if hasattr(e, 'reason'):  
                print 'Can\'t connect server.'  
                print 'reason: ', e.reason  
                return False
            elif hasattr(e, 'code'):  
                print 'Request error.'  
                print 'code:: ', e.code  
                return False
            else:  
                print 'Unkown error.'
                return False

        self.temppage=self.res.read()

    #----------------------------------------------------------------------
    def __ask(self):
        """判断是否登录成功"""
        if self.temppage=='':
            print 'No content'
            return False

        if self.temppage.find(self.rightkeyword) >=0:
            print ('Login succeed')
            return True
        elif self.temppage.find(self.wrongkeyword) >=0:
            print ('Login failed')
            return False
        else :
            print 'Unkown page.'
            return False
    #----------------------------------------------------------------------
    def printcookie(self):
        """输出cookies"""
        print '*'*5,'The cookies are:','*'*5
        for i in self.cookie:
            print i.name,'=',i.value
        print '*'*(10+len('The cookies are:'))       
        
    #----------------------------------------------------------------------
    def printpage(self,webcode='utf-8',syscode='GBK'):
        """打印网页源代码"""
        print self.temppage.decode(webcode).encode(syscode)


    #----------------------------------------------------------------------
    def __del__(self):
        """析构函数"""
        self.data=None
        self.temppage=None
        self.debuglevel=0
        self.cookie=None



'''
if __name__ == "__main__":
      
     if len(sys.argv) < 3:
           print "Usage: %s  <username> <password>" % sys.argv[0]
           raise SystemExit
       name = sys.argv[1]
       password = sys.argv[2]
      
    url="http://10.1.1.76:8080/controller/system/User/login"
    name="chenjun@ccs.org.cn"
    password="CCSwz123"
    userpass={'username':name,'password':password,'jpolite_key_req_version':'0.1'}
    webcode='utf-8' #指定网页编码
    rightkeyword='SUCCESS'.decode('utf-8').encode(webcode)
    wrongkeyword='登陆失败，请确认用户名密码及邮箱是否正确'.decode('utf-8').encode(webcode)


    session = GetRules()
    session.login(url,userpass,rightkeyword,wrongkeyword)
    session.printcookie()
    session.printpage(webcode,'GBK')
'''
#----------------------------------------------------------------------
def test1():
    """"""
    url="http://10.1.1.76:8080/controller/system/User/login"
    name="chenjun@ccs.org.cn"
    password="CCSwz123"
    userpass={'username':name,'password':password,'jpolite_key_req_version':'0.1'}
    webcode='utf-8' #指定网页编码
    rightkeyword='SUCCESS'.decode('utf-8').encode(webcode)
    wrongkeyword='登陆失败，请确认用户名密码及邮箱是否正确'.decode('utf-8').encode(webcode)


    session = GetRules()
    session.login(url,userpass,rightkeyword,wrongkeyword)
    session.printcookie()
    session.printpage(webcode,'GBK')
    
    
    
test1()